package ichubcli

import (
	"fmt"
	"gitee.com/ichub/webcli/common/base/basedto"
	"gitee.com/ichub/webcli/common/base/baseutils/jsonutils"
	"gitee.com/ichub/webcli/common/base/baseutils/stringutils"
	"gitee.com/ichub/webcli/common/base/pagedto/pagedbdto"
	"gitee.com/ichub/webcli/common/base/pageesdto"
	"gitee.com/ichub/webcli/common/ichubconfig"
	"gitee.com/ichub/webcli/common/ichubcontext"
	"gitee.com/ichub/webcli/common/ichublog"
	"gitee.com/ichub/webcli/ichubengine/ichubclicommon"
	"gitee.com/ichub/webcli/model"
	"github.com/sirupsen/logrus"
	"github.com/stretchr/testify/suite"
	"strings"
	"testing"
)

// 依赖 suite.Suite
type TestWebSuite struct {
	suite.Suite
	ruleClient *RuleClient
	value      int
}

func (suite *TestWebSuite) Check(exp interface{}, real interface{}, msg ...string) {
	fmt.Println("real=", real)
	expect := stringutils.ToStringWith(exp)
	r := stringutils.ToStringWith(real)
	suite.Equal(expect, r, msg)
}

// 用于 'go test' 的入口
func TestWebSuites(t *testing.T) {
	suite.Run(t, new(TestWebSuite))
}

// 每个测试运行前，会执行
func (suite *TestWebSuite) SetupTest() {
	//baseutils.FindRootDir()
	ichublog.InitLogrus()
	suite.value = 5
	suite.T().Log("SetupTest")
	var webClientCfg = ichubconfig.New(ichubconfig.ConfigfileIchubengine)
	var webClientDto = webClientCfg.ReadIchubWebClient()
	suite.ruleClient = New(webClientDto)

}
func (suite *TestWebSuite) TearDownTest() {
	suite.value = 5
	//	suite.T().Log("TearDownTest")
}
func (suite *TestWebSuite) SetupSuite() {
	fmt.Println("Suite setup")
	fmt.Println("领域驱动设计，测试驱动开发!")

}

func (suite *TestWebSuite) TearDownSuite() {
	fmt.Println("Suite teardown")
}

// 所有以“Test”开头的方法，都是一个测试
func (suite *TestWebSuite) Test0001_PostRule() {
	//prepare
	var ruleData = ichubclicommon.NewRuleData(rule1, param1)
	//test
	var i = 4
	var result *basedto.IchubResult

	for i > 0 {
		result = suite.ruleClient.PostRule(ruleData)
		i--
	}
	//Checks
	suite.Equal(200, result.Code)
	suite.Equal(float64(14000), result.ValueByKey("Pay"))
	logrus.Info(result)
	ichublog.IchubLog.Println(result)
}

func (suite *TestIchubServerSuite) Test0002_PostRuleBatch() {

	//prepare
	var ruleData = ichubclicommon.NewRuleData(rule1, param)
	//test
	results := suite.ruleClient.PostRuleBatch([]*ichubclicommon.RuleData{ruleData, ruleData.Clone()})

	//Checks
	suite.Equal(200, results.Code)
	suite.Equal(float64(14000), results.Data[0].ValueByKey("Pay"))
	logrus.Info(results)
}

func (suite *TestWebSuite) Test0003_EmployeJson() {
	suite.T().Log("testemp")
	var emp = &Employee{
		Id:   1,
		Name: "leijmdas",
	}
	emp.Pay = &Pay{
		Id:     1,
		Month:  202401,
		Salary: 18000,
	}
	emp.InitProxy(emp)
	fmt.Println("u=", jsonutils.ToJsonPretty(emp))

	m, _ := jsonutils.MapFromJson(jsonutils.ToJsonStr(emp))
	fmt.Println(jsonutils.ToJsonPretty(m))
	var e1 = emp.Clone().(*Employee)
	fmt.Println(e1)

}

const ruleDefine = `
//in out 参数 

rule "ComputeTax0001" "计算工资税" salience 0
begin

    Pay=In.GetMap("Pay")	
    Salary=Pay.GetParam("Salary")
	
 	Tax = 0
	if Salary.ToInt64() > 10000 {
		Tax =  200 
	} else {
		Tax = 100
	}
	Username=In.GetMap("Username")
	Out.SetParam("Tax",Tax)
    Out.SetReturnValue(0)
	Out.SetParam("Username",Username)
   	   
end`

type Employee struct {
	basedto.BaseEntity
	Id   int
	Name string
	Pay  *Pay       `json:"Pay,omitempty"`
	User *IchubUser `json:"Username,omitempty"`
}

func (emp *Employee) ToString() string {
	return emp.BaseEntity.ToString()
}

type Pay struct {
	Id     int
	Month  int `json:"Month,omitempty"`
	Salary int
}

type IchubUser struct {
	Id   int
	Name string
	Age  int
}

func UserComparator(a, b interface{}) int {

	return strings.Compare(a.(*IchubUser).Name, b.(*IchubUser).Name)

}
func (u *IchubUser) ValueOf(another *IchubUser) {
	*u = *another
}

func NewEmployee() *Employee {
	return &Employee{}
}
func (suite *TestWebSuite) Test0004_ComplexStruct() {

	var emp = &Employee{
		Id:   1,
		Name: "leijmdas",
	}
	emp.InitProxy(emp)
	emp.Pay = &Pay{
		Id:     1,
		Month:  202401,
		Salary: 18000,
	}

	emp.User = &IchubUser{
		Id:   1234,
		Name: "leijmdas@163.com",
		Age:  43,
	}

	var ruleData = &ichubclicommon.RuleData{
		Rule:  ruleDefine,
		Param: emp.ToString(),
	}
	fmt.Println(ruleData.ToString())
	//test
	result := suite.ruleClient.PostRule(ruleData)
	//Checks
	suite.Equal(200, result.Code) //suite.Equal(float64(200), result.ValueByKey("Tax"))
	suite.Check(200, result.ValueByKey("Tax"), "tax = 200")

}
func (suite *TestWebSuite) Test0006_DoHelp() {
	//prepare

	//test
	result := suite.ruleClient.DoHelp()

	//Checks
	suite.Equal(200, result.Code)
	fmt.Println(result.ToString())
}

func (suite *TestWebSuite) Test0007_Help() {
	//prepare

	//test
	result := suite.ruleClient.Help()

	//Checks
	//suite.Equal(200, result.Code)
	fmt.Println(result.ToString())
	var ret = basedto.JsonResult{Code: 200}
	fmt.Println(ret.String())
}

const ruleDefineGlobalCfg = `
rule "query-general-config-001" "通用配置查询" salience 0
begin
	    
    shopId=In.GetParam("shop_id")    
    memberId=In.GetParam("member_id")   
    ruleKey=In.GetParam("rule_key")

	gconfig=GeneralConfig()
    gconfig.ShopId=shopId.ToInt64()
    gconfig.MemberId=memberId.ToInt64()
    gconfig.RuleKey = ruleKey.ToString() 
    result=gconfig.Query()

    Out.SetReturnValue(200)
    Out.SetReturnMsg("计算成功！")
    Out.SetParam("Data",result)                    
	 
end`
const paramGlobalCfg = ` {
	"shop_id": 111110,
	"object_id" : 0,
	"object_type" : "1"
}`

// 通用接口
func (suite *TestWebSuite) Test0008_PostRuleGeneralConfig() {
	//prepare
	var ruleData = &ichubclicommon.RuleData{
		Rule:  ruleDefineGlobalCfg,
		Param: paramGlobalCfg,
	}
	//test
	result := suite.ruleClient.PostRule(ruleData)
	logrus.Println(result.ToString())
	//check
	suite.Equal(200, result.Code)
	ichubcontext.CommonContext.Log()
	logrus.Println(result.DataIfMapParams().GetParams("Data").Params)
}
func (suite *TestWebSuite) Test0011_PostRuleFuncId() {

	//test
	result := suite.ruleClient.PostRuleFunc(ichubclicommon.FUNC_SNOWFLAKE, "{}")

	//check
	suite.Equal(200, result.Code)
	logrus.Println(jsonutils.ToJsonPretty(result))
}

func (suite *TestWebSuite) Test0012_PostRuleFuncConfig() {

	//test
	result := suite.ruleClient.PostRuleFunc(ichubclicommon.FUNC_CONFIG, paramGlobalCfg)

	//check
	suite.Equal(200, result.Code)

	logrus.Println(result.ToString())
}
func (suite *TestWebSuite) Test0014_PostRuleFuncConfigClientParams() {
	const param = ` {
		"shop_id": 0,
		"object_id" : 0,
		"object_type" : "1"
	}`
	params := ichubclicommon.NewIchubClientParams()
	params.Put("shop_id", 10)
	params.Put("object_id", 10)
	params.Put("object_type", 1)
	ps := ichubclicommon.NewIchubClientParams()
	ps.Put("attr1", 1)
	ps.Put("attr21", 21)
	ps.Put("attr31", 31)
	params.Put("cfg", ps.Params)

	logrus.Info(params.ToParams())
	//test
	result := suite.ruleClient.PostRuleFunc(ichubclicommon.FUNC_ESQUERY, params.ToParams())

	//check
	suite.Equal(200, result.Code)

	logrus.Info(result)
}
func (suite *TestWebSuite) Test0015_PostRuleFunclist() {

	//test
	result := suite.ruleClient.PostRuleFunc(ichubclicommon.FUNC_LISTFUNCS, ichubclicommon.FUNC_PARAM_EMPTY)

	//check
	suite.Equal(200, result.Code)
	fmt.Println(jsonutils.ToJsonPretty(result.Data))
}
func (suite *TestWebSuite) Test0016_EsClientQuery() {
	//req
	var req = pageesdto.NewEsRequest(2, 1)
	req.IndexName = "ichub_sys_dept"
	//esClient.Eq("dept_id", "553251751520632832")
	//esClient.OrderBy("dept_id", "desc")
	//	"email": "leijmdas@163.com",
	//	esClient.Like("email", "s@236")
	req.Like("email", "leijmdas@163.com")
	req.Between("dept_id", []interface{}{"553263667185975296", "553263667185975296"})

	//test
	result := suite.ruleClient.EsClientQuery(req)

	//check
	suite.Equal(200, result.Code)
	ichublog.IchubLog.Println(result)
	logrus.Info(result.ToPrettyString())
}

func (suite *TestWebSuite) Test0017_DbClientQuery() {
	//dbRequest
	var dbRequest = pagedbdto.NewIchubPageDbRequest()
	dbRequest.PageSize = 2
	dbRequest.TableName = "employee"
	dbRequest.TimeToInt = true //	dbRequest.FieldsName = "rule_id,name"
	//dbRequest.Eq("dept_id", "553251751520632832")	//dbRequest.OrderBy("dept_id", "desc") 	//	"email": "leijmdas@163.com",
	//	dbRequest.Like("email", "s@236")
	// dbRequest.Like("email", "leijmdas@163.com")
	//	dbRequest.Between("rule_id", []any{"1", "266"})

	//test
	result := suite.ruleClient.DbClientQuery(dbRequest) //check
	suite.Equal(200, result.Code)
	logrus.Info(result, dbRequest.ToPrettyString())
	logrus.Info(jsonutils.ToJsonPretty(result.GetDbResult()))
	var emps []model.EmployeeDto = []model.EmployeeDto{}
	result.DbResultTo(&emps)
	ichublog.Log("emps=", jsonutils.ToJsonPretty(emps))
}
func (suite *TestWebSuite) Test0018_DbClientQuery() {
	//dbRequest
	var dbRequest = pagedbdto.NewIchubPageDbRequest()
	dbRequest.PageSize = 2
	dbRequest.TableName = "employee"
	dbRequest.TimeToInt = false //	dbRequest.FieldsName = "rule_id,name"
	//dbRequest.Eq("dept_id", "553251751520632832")	//dbRequest.OrderBy("dept_id", "desc") 	//	"email": "leijmdas@163.com",
	//	dbRequest.Like("email", "s@236")
	// dbRequest.Like("email", "leijmdas@163.com")
	//	dbRequest.Between("rule_id", []any{"1", "266"})

	//test
	result := suite.ruleClient.DbClientQuery(dbRequest) //check
	suite.Equal(200, result.Code)
	logrus.Info(result, dbRequest.ToPrettyString())
	logrus.Info(jsonutils.ToJsonPretty(result.GetDbResult()))
	var emps []model.Employee // = []model.EmployeeDto{}
	result.DbResultTo(&emps)
	ichublog.Log("emps new=", jsonutils.ToJsonPretty(emps))
}
